package fr.umlv.m2.jee.spij.web.file.download;

import fr.umlv.m2.jee.spij.persistence.education.Lesson;
import fr.umlv.m2.jee.spij.persistence.education.dao.HibernateLessonDAO;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.webflow.context.ExternalContext;
import org.springframework.webflow.execution.Event;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

/**
 *
 */
@Component("downloader")
public class DownloaderLessonAction {

    private final Log log = LogFactory.getLog(DownloaderLessonAction.class);

    @Autowired
    private HibernateLessonDAO lessonDAO;

    public Event download(ExternalContext requestContext, long id) throws Exception {
        log.error("Rentre dans la methode");

        // log.error(requestContext);
        // final long lessonID = requestContext.getAttributes().getLong("lessonID");
        // final long lessonID = requestContext.getRequestParameters().getLong("lessonID");
        final Lesson lesson = lessonDAO.findById(id);

        final HttpServletResponse response = (HttpServletResponse)
                requestContext.getNativeResponse();

        response.setContentType("application/pdf");
        try {
            ServletOutputStream os = response.getOutputStream();
            os.write(lesson.getFileData());
            os.flush();
            os.close();
            response.flushBuffer();
            requestContext.recordResponseComplete();
        } catch (Exception e) {
            log.error("\n Failure : " + e.toString() + "\n");
        }
        return null;  //To change body of implemented methods use File | Settings | File Templates.
    }
}
